package com.tfxy.hxl.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tfxy.hxl.R;
import com.tfxy.hxl.entity.Activity;
import com.tfxy.hxl.entity.Booking;
import com.tfxy.hxl.service.ActivityService;
import com.tfxy.hxl.service.BookingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@RestController
@RequestMapping("/booking")
public class BookingController {

    @Autowired
    private BookingService bookingService;

    @Autowired
    private ActivityService activityService;

    // 创建预约
    @PostMapping("/create")
    public R createBooking(@RequestBody Booking booking) {
        // 检查活动是否存在且状态正常
        Activity activity = activityService.getById(booking.getActivityId());
        if (activity == null) {
            return R.error().message("活动不存在");
        }
        if (activity.getStatus() != 1) {
            return R.error().message("活动已取消");
        }
        
        // 检查是否还有名额
        if (activity.getCurrentParticipants() >= activity.getMaxParticipants()) {
            return R.error().message("活动名额已满");
        }
        
        // 检查用户是否已经预约过该活动
        QueryWrapper<Booking> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", booking.getUserId())
                   .eq("activity_id", booking.getActivityId())
                   .eq("deleted", 0)
                   .in("status", 1, 2); // 已预约或已确认状态
        Booking existingBooking = bookingService.getOne(queryWrapper);
        if (existingBooking != null) {
            return R.error().message("您已经预约过该活动");
        }
        
        // 创建预约
        booking.setBookingTime(new Date());
        booking.setStatus(1); // 已预约
        booking.setPaymentStatus(0); // 未支付
        booking.setAmount(activity.getPrice());
        booking.setCreateTime(new Date());
        booking.setUpdateTime(new Date());
        
        boolean saved = bookingService.save(booking);
        if (saved) {
            // 更新活动的当前参与人数
            activity.setCurrentParticipants(activity.getCurrentParticipants() + 1);
            activityService.updateById(activity);
            return R.ok().message("预约成功");
        } else {
            return R.error().message("预约失败");
        }
    }
    // 分页查询用户的预约列表
    @GetMapping("/user/{userId}")
    public R getUserBookings(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size) {
        
        Page<Booking> page = new Page<>(current, size);
        QueryWrapper<Booking> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                   .eq("deleted", 0)
                   .orderByDesc("create_time");
        
        Page<Booking> result = bookingService.page(page, queryWrapper);
        
        return R.ok().data("bookings", result.getRecords())
                .data("total", result.getTotal())
                .data("current", result.getCurrent())
                .data("size", result.getSize());
    }

    // 根据ID查询预约详情
    @GetMapping("/{id}")
    public R getBookingById(@PathVariable Long id) {
        Booking booking = bookingService.getById(id);
        return booking != null ? R.ok().data("booking", booking) : R.error().message("预约不存在");
    }

    // 取消预约
    @PutMapping("/cancel/{id}")
    public R cancelBooking(@PathVariable Long id) {
        Booking booking = bookingService.getById(id);
        if (booking == null) {
            return R.error().message("预约不存在");
        }
        
        if (booking.getStatus() == 3) {
            return R.error().message("预约已取消");
        }
        
        // 取消预约
        booking.setStatus(3);
        booking.setUpdateTime(new Date());
        boolean updated = bookingService.updateById(booking);
        
        if (updated) {
            // 减少活动的当前参与人数
            Activity activity = activityService.getById(booking.getActivityId());
            if (activity != null) {
                activity.setCurrentParticipants(Math.max(0, activity.getCurrentParticipants() - 1));
                activityService.updateById(activity);
            }
            return R.ok().message("预约取消成功");
        } else {
            return R.error().message("预约取消失败");
        }
    }

    // 确认预约（管理员功能）
    @PutMapping("/confirm/{id}")
    public R confirmBooking(@PathVariable Long id) {
        Booking booking = bookingService.getById(id);
        if (booking == null) {
            return R.error().message("预约不存在");
        }
        
        booking.setStatus(2); // 已确认
        booking.setUpdateTime(new Date());
        boolean updated = bookingService.updateById(booking);
        return updated ? R.ok().message("预约确认成功") : R.error().message("预约确认失败");
    }

    // 支付预约
    @PutMapping("/pay/{id}")
    public R payBooking(@PathVariable Long id) {
        Booking booking = bookingService.getById(id);
        if (booking == null) {
            return R.error().message("预约不存在");
        }
        
        if (booking.getPaymentStatus() == 1) {
            return R.error().message("预约已支付");
        }
        
        booking.setPaymentStatus(1); // 已支付
        booking.setUpdateTime(new Date());
        boolean updated = bookingService.updateById(booking);
        return updated ? R.ok().message("支付成功") : R.error().message("支付失败");
    }
} 